package com.hutao.medical.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hutao.medical.common.config.ConfigProperties;
import com.hutao.medical.common.config.FunctionType;
import com.hutao.medical.common.util.DateUtil;
import com.hutao.medical.common.util.HttpClientUtil;
import com.hutao.medical.common.util.JsonUtils;
import com.hutao.medical.common.util.MD5;
import com.hutao.medical.common.util.Result;
import com.hutao.medical.commpoent.Config;
import com.hutao.medical.mapper.borrow.BorrowCheckRecordMapper;
import com.hutao.medical.mapper.borrow.BorrowFunctionMapper;
import com.hutao.medical.mapper.borrow.BorrowRecordMapper;
import com.hutao.medical.mapper.borrow.HospitalNoteMapper;
import com.hutao.medical.mapper.borrow.MedicalFunctionMapper;
import com.hutao.medical.pojo.borrow.BorrowCheckRecord;
import com.hutao.medical.pojo.borrow.BorrowFunction;
import com.hutao.medical.pojo.borrow.BorrowRecord;
import com.hutao.medical.pojo.borrow.HospitalNote;
import com.hutao.medical.pojo.borrow.MedicalFunction;
import com.hutao.medical.pojo.dto.MedBorrowDto;
import com.hutao.medical.query.BorrowQuery;
import com.hutao.medical.service.BorrowService;

@Service
public class BorrowServiceImpl implements BorrowService {

	/*@Autowired
	private Config config;*/

	@Autowired
	private ConfigProperties configProperties;
	
	@Autowired
	private BorrowRecordMapper borrowRecordMapper;

	@Autowired
	private BorrowCheckRecordMapper borrowCheckRecordMapper;
	
	@Autowired
	private HospitalNoteMapper hospitalNoteMapper;
	
	@Autowired
	private MedicalFunctionMapper medicalFunctionMapper;
	
	@Autowired
	private BorrowFunctionMapper borrowFunctionMapper;

	@Override
	public int insert(BorrowRecord record) {

		String uniqueKey = record.getUniqueKey();
		if (StringUtils.isNotEmpty(uniqueKey)) {
			BorrowRecord recordMsg = selectByUniqueKey(uniqueKey);
			if (recordMsg != null) {
				BorrowCheckRecord borrowCheckRecord = new BorrowCheckRecord();
				borrowCheckRecord.setBorrowRecordId(recordMsg.getId());
				borrowCheckRecord.setCheckStatus(1);
				borrowCheckRecord.setCreateTime(new Date());
				borrowCheckRecord.setApplyName(record.getOperator());
				borrowCheckRecordMapper.insertSelective(borrowCheckRecord);
			} else {
				record.setCreateTime(new Date());
				borrowRecordMapper.insertSelective(record);
				BorrowCheckRecord borrowCheckRecord = new BorrowCheckRecord();
				borrowCheckRecord.setBorrowRecordId(record.getId());
				borrowCheckRecord.setCheckStatus(1);
				borrowCheckRecord.setCreateTime(new Date());
				borrowCheckRecord.setApplyName(record.getOperator());
				borrowCheckRecordMapper.insertSelective(borrowCheckRecord);
			}

		}
		return 0;
	}

	@Override
	public BorrowRecord selectByUniqueKey(String uniqueKey) {

		return borrowRecordMapper.selectByUniqueKey(uniqueKey);
	}


//	@Override
//	public int selectApplyBorrowCountByKeyWords(BorrowQuery borrowQuery) {
//		return borrowRecordMapper.selectApplyBorrowCountByKeyWords(borrowQuery);
//	}

	@Override
	public int updateApplyStatus(BorrowFunction borrowFunction) {

		return borrowFunctionMapper.updateByPrimaryKeySelective(borrowFunction);
	}

	@Override
	public Map<String, Object> getMedResourceFile(String firstGuid, String applyName) {
		Map<String, Object> resultMap = new HashMap<>();
		// 存储图片url集合
		List<String> cachePicList = new ArrayList<>();
		// 存储住院信息集合
		List<Map<String, Object>> hospitalizationNotes = new ArrayList<>();
		// 通过firstGuid查询图片信息
		Map<String, String> param = new HashMap<>();
		param.put("firstGuid", firstGuid);
		String userJson = HttpClientUtil.doPost(configProperties.getMedicalManage().getHospResourceUrlByHttpClient(), param);
		Result result = JsonUtils.jsonToPojo(userJson, Result.class);
		Map<String, Object> dataMap = (Map<String, Object>) result.getData();
		// 查询不为空时
		if (MapUtils.isNotEmpty(dataMap)) {
			List<Map<String, Object>> scanFileMapList = (List<Map<String, Object>>) dataMap.get("scanFiles");
			hospitalizationNotes = (List<Map<String, Object>>) dataMap.get("hospitalizationNotes");
			if (CollectionUtils.isNotEmpty(scanFileMapList)) {
				// 循环生成水印
				for (Map<String, Object> map : scanFileMapList) {

					String fileName = (String) map.get("fileName");
					String fileUrl = (String) map.get("fileUrl");
					String secret = MD5.md5(fileUrl + fileName);
					System.out.println(fileName+fileUrl);

					// 调用sso生成图片水印
					Map<String, String> cachePicParam = new HashMap<>();
					cachePicParam.put("fileName", fileUrl + fileName);
					cachePicParam.put("secret", secret);
					try {
						cachePicParam.put("signature", URLEncoder.encode("中国人民解放军305医院", "utf-8"));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					
					String cachePicJson = HttpClientUtil.doPost(configProperties.getSso().getSeekMarkPicUrl(),
							cachePicParam);
					

					// 获取生成水印图片信息
					Result casheResult = JsonUtils.jsonToPojo(cachePicJson, Result.class);
					if (StringUtils.isNoneEmpty((String) casheResult.getData())) {
						cachePicList.add((String) casheResult.getData());
					}
				}
			}
		}
		resultMap.put("cachePicList", cachePicList);
		resultMap.put("hospitalizationNotes", hospitalizationNotes);

		return resultMap;
	}

	@Override
	public int updateApplyStatusBatch(BorrowCheckRecord borrowCheckRecord) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("checkStatus", borrowCheckRecord.getCheckStatus());
		map.put("checkTime", new Date());
		map.put("ids", borrowCheckRecord.getIds());
		map.put("checkMan", borrowCheckRecord.getCheckMan());

		return borrowCheckRecordMapper.updateApplyStatusBatch(map);
	}

	@Override
	public int selectBorrowMedByLoginNameAndDaysCount(MedBorrowDto medBorrowDto) {
		return borrowRecordMapper.selectBorrowMedByLoginNameAndDaysCount(medBorrowDto);
	}



	//导出借阅审批到excel
	@Override
	public List<Map<String, Object>> exportBorrowApproveToExcel(BorrowQuery borrowQuery) {
		
		return borrowRecordMapper.exportBorrowApproveToExcel(borrowQuery);
	}
	
	//导出借阅统计到excel
	@Override
	public List<Map<String, Object>> exportBorrowStaitcsToExcel(BorrowQuery borrowQuery) {

		return borrowRecordMapper.exportBorrowStaitcsToExcel(borrowQuery);
	}


	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public HospitalNote addHospitalNote(String firstGuid) {
		HospitalNote hospitalNote = new HospitalNote();
		if (hospitalNoteMapper.isExistHospitalNote(firstGuid) > 0) {
			hospitalNote = hospitalNoteMapper.getHospitalNoteByFirstGuid(firstGuid);
			return hospitalNote;
		}
		Map<String, String> param = new HashMap<>();
		param.put("firstGuid", firstGuid);

		String userJson = HttpClientUtil.doPost(configProperties.getMedicalManage().getGetMedRecordByFirstGuidPath(),
				param);
		Result result = JsonUtils.jsonToPojo(userJson, Result.class);
		Map<String, Object> dataMap = (Map<String, Object>) result.getData();
		if (MapUtils.isNotEmpty(dataMap)) {
			hospitalNote.setFirstGuid(firstGuid);
			hospitalNote.setName(dataMap.get("NAME") == null ? null : (String) dataMap.get("NAME"));
			hospitalNote.setCreateDate(new Date());
			hospitalNote.setMrId(dataMap.get("mrId") == null ? null : (String) dataMap.get("mrId"));
			hospitalNote.setOnlyId(dataMap.get("onlyId") == null ? null : (String) dataMap.get("onlyId"));
			hospitalNote.setIdNumber(dataMap.get("idCard") == null ? null : (String) dataMap.get("idCard"));
			hospitalNote.setOutHospitalOfficeCode(
					dataMap.get("outOfficeId") == null ? null : (Integer) dataMap.get("outOfficeId") + "");
			hospitalNote.setOutHospitalOfficeName(
					dataMap.get("outOfficeName") == null ? null : (String) dataMap.get("outOfficeName"));
			hospitalNote.setOutHospitalTypeCode(
					dataMap.get("outHospitalTypeId") == null ? null : (Integer) dataMap.get("outHospitalTypeId") + "");
			hospitalNote.setOutHospitalType(
					dataMap.get("outHospitalType") == null ? null : (String) dataMap.get("outHospitalType"));
			hospitalNote.setBirthday(
					dataMap.get("birthday") == null ? null : DateUtil.strToDate((String) dataMap.get("birthday")));
			hospitalNote.setOutHospitalDate(dataMap.get("outHospitalDate") == null ? null
					: DateUtil.strToDate((String) dataMap.get("outHospitalDate")));
			hospitalNoteMapper.insert(hospitalNote);
		}

		return hospitalNote;
	}

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int addMedRecordBorrow(HospitalNote hospitalNote, String currentUser) {
		MedicalFunction medicalFunction=new MedicalFunction();
		if(medicalFunctionMapper.isExistMedFunctionByFirstGuidAndFunType(hospitalNote.getFirstGuid(), FunctionType.borrow)>0){
			medicalFunction=medicalFunctionMapper.getMediFunctionIdFirstGuidAndFunType(hospitalNote.getFirstGuid(), FunctionType.borrow);
		}else{
			medicalFunction.setFunctionTypeId(FunctionType.borrow);
			medicalFunction.setCreateTime(new Date());
			medicalFunction.setFirstGuid(hospitalNote.getFirstGuid());
			medicalFunction.setStatus(1);
			medicalFunctionMapper.insertSelective(medicalFunction);
		}
		
		BorrowFunction borrowFunction = new BorrowFunction();
		borrowFunction.setBorrowMan(currentUser);
		borrowFunction.setCreateTime(new Date());
		borrowFunction.setMedicalFunctionId(medicalFunction.getId());
		borrowFunction.setCheckStatus(1);
		borrowFunctionMapper.insertSelective(borrowFunction);		
		return 0;
	}

	@Transactional(readOnly=true)
	@Override
	public Map<String, Object> getMedicalBorrowListToCheck(MedBorrowDto medBorrowDto) {
		medBorrowDto.setFunctionType(FunctionType.borrow);
		Map<String,Object> map =new HashMap<>();
		List<Map<String,Object>> borrowMedToCheckList = borrowFunctionMapper.getMedicalBorrowList(medBorrowDto);
		int totalCount = borrowFunctionMapper.getMedicalBorrowListCount(medBorrowDto);
		map.put("borrowMedToCheckList", borrowMedToCheckList);
		map.put("totalCount", totalCount);
		return map;
	}

	@Transactional(readOnly=true)
	@Override
	public Map<String, Object> selectBorrowMedByLoginNameAndDays(MedBorrowDto medBorrowDto) {
		Map<String,Object> map = new HashMap<>();
		medBorrowDto.setBorrowDays(15);
		medBorrowDto.setCheckStatus(2);
		medBorrowDto.setFunctionType(FunctionType.borrow);
		List<Map<String,Object>> borrowSearchList = borrowFunctionMapper.getMedicalBorrowSearchList(medBorrowDto);
		int totalCount = borrowFunctionMapper.getMedicalBorrowSearchListCount(medBorrowDto);
		map.put("borrowSearchList", borrowSearchList);
		map.put("totalCount", totalCount);
		return map;
	}
	
	@Transactional(readOnly=true)
	@Override
    public List<Map<String,Object>> getMedicalBorrowSearchList_mobile(Map<String, Object> params) {
    	return borrowFunctionMapper.getMedicalBorrowSearchList_mobile(params);
    }
    
	@Transactional(readOnly=true)
	@Override
    public  int getMedicalBorrowSearchListCount_mobile(Map<String, Object> params) {
    	return borrowFunctionMapper.getMedicalBorrowSearchListCount_mobile(params);
    }

	@Transactional(readOnly=true)
	@Override
	public Map<String, Object> selectApplyBorrowByKeyWords(MedBorrowDto medBorrowDto) {
		Map<String,Object> map = new HashMap<>();
		medBorrowDto.setFunctionType(FunctionType.borrow);
		//medBorrowDto.setCheckStatus(2);
		List<Map<String,Object>> borrowRecordList = borrowFunctionMapper.getMedBorrowRecordList(medBorrowDto);
		int totalCount = borrowFunctionMapper.getMedBorrowRecordListCount(medBorrowDto);
		map.put("borrowRecordList", borrowRecordList);
		map.put("totalCount", totalCount);
		return map;
	}

	@Transactional(readOnly=true)
	@Override
	public List<Map<String,Object>> getBorrowedFirstGuidList(String borrowMan) {
		
		return borrowFunctionMapper.getBorrowedFirstGuidList(borrowMan);
	}

	


}
